const response = require('../../utils/response');
const UploadService = require('../../services/system/uploadService');
const logger = require('../../utils/logger');
require('dotenv').config();

class UploadController {
    static async uploadFile(ctx) {
        try {
            const file = ctx.request.files?.attach;
            await UploadService.validateFile(file);
            
            // 使用安全的文件名
            const secureFilename = UploadService.generateSecureFilename(file.originalFilename);
            
            // 重命名文件为安全文件名
            const fs = require('fs').promises;
            const path = require('path');
            const oldPath = file.filepath;
            const newPath = path.join(path.dirname(oldPath), secureFilename);
            
            try {
                await fs.rename(oldPath, newPath);
                // 更新文件对象中的文件名
                file.newFilename = secureFilename;
                file.filepath = newPath;
            } catch (renameErr) {
                logger.error(`文件重命名失败: ${renameErr.message}`);
                // 如果重命名失败，继续使用原始文件
            }
            
            logger.info(`文件上传成功: ${file.originalFilename} -> ${file.newFilename}`);
            
            response.success(ctx, {
                data: {
                    name: file.originalFilename,
                    url: file.newFilename,
                    id: file.newFilename
                }
            });
        } catch (err) {
            logger.error(`文件上传失败: ${err.message}`);
            response.error(ctx, { message: err.message });
        }
    }

    static async deleteFiles(ctx) {
        try {
            const { ids } = ctx.request.body;
            if (!ids?.length) {
                logger.warn('删除文件请求缺少文件ID');
                return response.error(ctx, { message: '缺少文件ID' });
            }

            // 限制一次删除的文件数量
            if (ids.length > 100) {
                logger.warn(`尝试一次性删除过多文件: ${ids.length}个`);
                return response.error(ctx, { message: '一次最多只能删除100个文件' });
            }

            const results = await Promise.all(ids.map(id => UploadService.deleteFile(id)));
            const success = results.filter(r => r.success);
            const errors = results.filter(r => !r.success);

            if (errors.length > 0) {
                logger.warn(`部分文件删除失败: ${errors.length}个`);
                response.error(ctx, {
                    message: '部分文件删除失败',
                    data: { success: success.map(s => s.fileId), errors }
                });
            } else {
                logger.info(`所有文件删除成功: ${success.length}个`);
                response.success(ctx, {
                    message: '所有文件删除成功',
                    data: success.map(s => s.fileId)
                });
            }
        } catch (err) {
            logger.error(`批量删除文件时发生错误: ${err.message}`);
            response.error(ctx, { message: '服务器内部错误' });
        }
    }
}

module.exports = UploadController;
